<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\circle;

use app\api\model\dao\Circle;
use app\api\model\dao\UserFollow;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class AddCircle extends PageBase
{

    private $objCircle;
    private $objUserFollow;

    public function __construct()
    {
        parent::__construct();

        $this->objCircle = new Circle();
        $this->objUserFollow = new UserFollow();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'category_id' => 'require',
            'name' => 'require|min:4|max:8',
            'briefing' => 'require|min:10',
            'reason' => 'require',
        ];
        $msg = [
            'category_id.require' => '圈子必须归属分类',
            'name.require' => '圈子名称必须填写',
            'name.min' => '圈子名称不得少于4个字符',
            'name.max' => '圈子名称不能多于8个字符',
            'briefing.require' => '圈子介绍必须填写',
            'briefing.min' => '圈子介绍不得少于10字符',
            'reason.require' => '圈子申请理由必须填写',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function myExcute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            throw new Exception('check token fail...', Error::ERR_NO_AUTH);
        }

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            throw new Exception($ret, Error::ERR_CUSTOM);
        }

        $arrCond = [
            'category_id' => ['=', $param['category_id']],
            'name' => ['=', $param['name']],
            'is_delete' => ['=', Flag::CONST_CIRCLE_DELETE_NOT],
        ];
        $ret_circle = $this->objCircle->getCircle($arrCond, ['id']);
        if (!empty($ret_circle)) {
            throw new Exception('data is exist', Error::ERR_DATA_EXIST);
        }

        $param['creator'] = $this->user_id; // 申请者id，userid，目前暂时写死
        $param['update_time'] = time();
        $param['create_time'] = time();

        $insertID = $this->objCircle->addCircle($param);
        if (false === $insertID) {
            throw new Exception('add circle fail...', Error::ERR_SYS);
        }

        // 自己关注自己的圈子
        $input = [
            'userid' => $this->user_id,
            'follow_type' => Flag::CONST_FOLLOW_CIRCLE,
            'follow_id' => $insertID,
            'date' => date('Ymd'),
            'create_time' => time()
        ];
        $ret = $this->objUserFollow->follow($input);
        if (false === $ret) {
            Log::error(__METHOD__ . ' follow fail.[param:' . json_encode($input) . ']');
        }

    }
}
